//
//  Person.m
//  001-消息转发机制
//
//  Created by hzg on 2018/4/26.
//  Copyright © 2018年 tz. All rights reserved.
//

#import "Person.h"
#import <objc/runtime.h>
#import "Dog.h"

@implementation Person



// 1. 动态方法解析

+ (BOOL) resolveClassMethod:(SEL)sel {
//    NSString* methodName = NSStringFromSelector(sel);
//    if ([methodName isEqualToString:@"sendMessage:"]) {
//        return class_addMethod(object_getClass(self), sel, (IMP)sendMessage, "v@:@");//class_addMethod(self, sel, (IMP)sendMessage, "v@:@");
//    }
    return NO;
}

//+ (BOOL) resolveInstanceMethod:(SEL)sel {
//
//    NSString* methodName = NSStringFromSelector(sel);
//    if ([methodName isEqualToString:@"sendMessage:"]) {
//        return class_addMethod(self, sel, (IMP)sendMessage, "v@:@");
//    }
//    return NO;
//}

void sendMessage(id self, SEL _cmd, NSString* message) {
    NSLog(@"%@", message);
}

- (id) forwardingTargetForSelector:(SEL)aSelector {
//    NSString* methodName = NSStringFromSelector(aSelector);
//    if ([methodName isEqualToString:@"sendMessage:"]) {
//        return [[Dog alloc] init];
//    }
    return [super forwardingTargetForSelector:aSelector];
}

// 3. 1)方法签名
- (NSMethodSignature*) methodSignatureForSelector:(SEL)aSelector {
    NSString* methodName = NSStringFromSelector(aSelector);
    
    if ([methodName isEqualToString:@"sendMessage:"]) {
        return [NSMethodSignature signatureWithObjCTypes:"v@:@"];
    }
    return [super methodSignatureForSelector:aSelector];
}

// 3. 2) 消息转发
- (void) forwardInvocation:(NSInvocation *)anInvocation {
//    SEL sel = [anInvocation selector];
//    Dog* dog = [Dog new];
//    if ([dog respondsToSelector:sel]) {
//        [anInvocation invokeWithTarget:dog];
//    } else {
//
//    }
    [super forwardInvocation:anInvocation];
}

- (void) doesNotRecognizeSelector:(SEL)aSelector {
    NSLog(@"消息无法处理");
}


@end
